package model;

import util.AppUtil;
import util.SmsSend;
import util.UserUtil;

import java.util.Map;
import java.util.Random;

import com.aliyuncs.dysmsapi.model.v20170525.SendSmsResponse;
import com.aliyuncs.exceptions.ClientException;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Model;
import com.jfinal.plugin.redis.Cache;
import com.jfinal.plugin.redis.Redis;

import constant.Msg;

public class User extends Model<User> {
	private static final long serialVersionUID = 1L;
	public static final User dao = new User();
	public static final String getCountSql = "select count(*) as num from users where 1=1;";/* 数据交互 *//* select */
	public static final String getOpenIdSql = "select * from users where wechatid=?;";
	public static final String bindSql = "update users set phone=? where id=?;";
	public static int i = 10000;
	
	public static Cache userCache= Redis.use("userCache");
	
	
	public String selectById(Integer id) {
		try {
			User user = User.dao.findById(id);
			return AppUtil.modelToJson(user);
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
	}
	
	/* 登录和注册 */
	public String registerLogin(String code){
		String openid = UserUtil.getWechatId(code);
		String token = new Random().nextInt(89999999)+10000000+""+new Random().nextInt(89999999)+10000000+""+System.currentTimeMillis();
		if(openid==null) return Msg.ERROR_OPENID_NOT_FIND;
		
		if(User.dao.find(getOpenIdSql, openid).isEmpty()){
			User newUser = new User().set("wechatid", openid)
					.set("create_time", (int) (System.currentTimeMillis() / 1000));
			if(newUser.save()){
				userCache.set(token, newUser.getInt("id"));
				return "{\"code\": 0,\"msg\": \"成功注册\", \"data\":[], \"token\":\""+token+"\"}";
			}else{return Msg.ERROR_REGISTER;}
		}else{
			User user = User.dao.find(getOpenIdSql, openid).get(0);
			userCache.set(token, user.getInt("id"));
			return "{\"code\": 0,\"msg\": \"成功登录\", \"data\":[], \"token\":\""+token+"\"}";
		}
	}
	
	
	/* delete */
	public boolean delete(Integer id) {
		try {
			User.dao.deleteById(id);
			return true;
		} catch (Exception e) {
			e.printStackTrace();
			return false;
		}
	}
	
	/* update */
	public String update(User user) {
		try {
			StringBuffer updateSql = new StringBuffer("update users set ");
			Map<String, String> attrMap = AppUtil.getAttr(user);
			for (Map.Entry<String, String> entry : attrMap.entrySet()) {
				if(entry.getValue()!=null){
					updateSql.append(entry.getKey() + "=");
					if (!AppUtil.isNum(entry.getValue())) {
						updateSql.append("\"" + entry.getValue() + "\"");
					} else {
						updateSql.append(entry.getValue());
					}
					updateSql.append(",");
				}
			}
			updateSql.deleteCharAt(updateSql.length() - 1);
			updateSql.append(" where id=" + user.getStr("id"));
			System.out.println(updateSql.toString());
			Db.update(updateSql.toString());
			return AppUtil.modelToJson(User.dao.findById(user.getStr("id")));
		} catch (Exception e) {
			e.printStackTrace();
			return Msg.ERROR_UNKNOWN;
		}
	}
	
	public String update(Integer id, String nickname, String avatarUrl, String city, String province,
			String country, String language, String gender) {
		try {
			System.out.println(id+nickname+avatarUrl+city+province+country+language+gender);
			User user = new User()
					.set("id", id)
					.set("nickname", nickname)
					.set("avatar", avatarUrl)
					.set("city", city)
					.set("province", province)
					.set("country", country)
					.set("language", language)
					.set("gender", gender)
					.set("update_time",
							(int) (System.currentTimeMillis() / 1000));
			return update(user);
		} catch (Exception e) {
			e.printStackTrace();
			return Msg.ERROR_UNKNOWN;
		}
	}
	
	
	
	
	/*
	 * 绑定手机
	 * 1. 发送验证码
	 * 2. 验证和绑定手机
	 */
	public String sms(String phone){
		int validCode = new Random().nextInt(8999)+1000;
		while(userCache.get(validCode)!=null) validCode = new Random().nextInt(8999)+1000;
		SendSmsResponse response = null;
		try {
			response = SmsSend.sendSms(phone, validCode);
			if(response.getCode() != null && response.getCode().equals("OK")) {
				userCache.set(validCode, 1);
				userCache.expire(validCode, 300);//timeout = 5min
	            System.out.println("发送成功");
	            return Msg.SUCCESS_EXECUTE;
	        }else{
	        	return Msg.ERROR_FAIL_SEND;
	        }
		} catch (ClientException e) {
			e.printStackTrace();
			return Msg.ERROR_UNKNOWN;
		}
	}

	public String bind(String phone, String validCode, Integer id) {
		try {
			if(userCache.get(validCode)!=null){
				userCache.del(validCode);
				Db.update(bindSql,phone,id);
				return Msg.SUCCESS_EXECUTE;
			}
			return Msg.ERROR_VALIDCODE;
		} catch (Exception e) {
			e.printStackTrace();
			return Msg.ERROR_UNKNOWN;
		}
	}
	
	/* 
	 * 工具部分 
	 */
	
	/*public void test(){
		userCache.set("123456", "aaa");
		System.out.println(userCache.get("123456"));
		System.out.println("----------------------------");
		userCache.del("123456");
		System.out.println(userCache.get("123456"));
		System.out.println("----------------------------");
		userCache.set("gggg", 2);
		userCache.expire("gggg", 1);
		System.out.println(userCache.get("gggg"));
		System.out.println("----------------------------");
		try {
			Thread.sleep(1000);
		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		System.out.println(userCache.get("gggg"));
		System.out.println("----------------------------");
		userCache.expire("gggg", 1000);
		
	}*/
	
	/*
	 * 获取总条数
	 */

	public int getCount() {
		int num = 0;
		num = Db.find(getCountSql).get(0).getInt("num");
		return num;
	}

	public int getPage(Integer length) {
		int num = getCount();
		if (num == 0)
			return 0;
		return num % length == 0 ? num / length : (num / length) + 1;
	}
	
	/* 验证函数 */
	
	/* 偏移量超出检测 */

	public boolean checkOffsetOut(Integer offset) {
		if (offset >= getCount())
			return false;
		else
			return true;
	}
}
